import { MD5 } from "crypto-js";
export function getPwdMD5Str(pwd: string) {
  let str = MD5(pwd + MD5(pwd)).toString();
  str = str.substring(0, 16);
  return str;
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time: any, cFormat?: string | null) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key as keyof typeof formatObj];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time: number, option: string | null) {
  if (("" + time).length === 10) {
    time = parseInt(time+"") * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d.getTime()) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

export function getQueryString(url: string, name: string) {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  const r = url.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url: string) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj: any = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str: string) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (let i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * 对象参数的处理
 * @param data
 * @returns {string}
 */
export function getParams(data: any) {
  if (!data) return "";
  return Object.keys(data)
    .map((k) => {
      const val = data[k];
      switch (true) {
        case val === null:
        case typeof val === "undefined":
          return "";
        case Array.isArray(val):
          return val
            .map(
              (v) => encodeURIComponent(k + "[]") + "=" + encodeURIComponent(v)
            )
            .join("&");
        default:
          return encodeURIComponent(k) + "=" + encodeURIComponent(val);
      }
    })
    .filter((v) => !!v)
    .join("&");
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type: string) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce <F extends Function>(func: F, wait: number, immediate: boolean) : (...args: any[]) => any {
  let timeout: number | null = null;
  let args: any[] | null = null;
  let context: any | null = null;
  let timestamp: number = 0;
  let result: any;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last) as unknown as number;
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args: any) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait) as unknown as number;
    if (callNow) {
      result = func.apply(context as any, args);
      context = args = null;
    }

    return result;
  };
}


/**
 * @param {*} val
 * @returns {String}
 */
export function getTypeOf(val: any) {
  return Object.prototype.toString
    .call(val)
    .toLocaleLowerCase()
    .replace("[object ", "")
    .replace("]", "");
}

export function compareVersion(p1: string = "", p2: string = "") {
  if (p1 === p2) {
    return 0;
  }
  const v1: string[] = p1.split(".");
  const v2: string[] = p2.split(".");
  const len = Math.max(v1.length, v2.length);
  while (v1.length < len) {
    v1.push("0");
  }
  while (v2.length < len) {
    v2.push("0");
  }
  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i]);
    const num2 = parseInt(v2[i]);
    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }
  return 0;
}
/**
 * 比较版本号
 * @param {String} v1 
 * @param {String} v2
 * @param {String} result 0 包含v2返回true; 1 大于v2返回true
 * @returns {Boolean}
 */
export function passVersion (v1 = '', v2 = '', result = 0) {
  return compareVersion(v1, v2) >= result
}
/**
 * 复制文本
 * @param {String} text
 * @returns
 */
export function copyText(text: string) {
  const el = document.createElement("textarea");
  el.value = text;
  el.readOnly = true;
  el.style.position = "absolute";
  el.style.left = "-999999px";
  el.style.top = "-999999px";
  document.body.append(el);
  el.select();
  const state = document.execCommand("copy");
  setTimeout(() => {
    el.remove();
  }, 350);
  return state;
}

export function formatVersion(val: string) {
  if (!val) return "";
  let version = val;
  const len = version.split(".").length;
  if (len < 4) {
    version += ".0";
  }
  return version;
}

export const ISO8601 = function (d: any) {
  if (!d) d = new Date();
  return parseTime(d, "{y}-{m}-{d}T{h}:{i}:{s}." + d.getMilliseconds());
}
